import 'dart:async';

import 'package:dartx/dartx.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart';
import 'package:realm/realm.dart';
import 'package:sgy_flutter/ble/HardwareVersion.dart';
import 'package:sgy_flutter/ble/ble_manager.dart';
import 'package:sgy_flutter/ble/right_ble_manager.dart';
import 'package:sgy_flutter/database/device_entity.dart';
import 'package:sgy_flutter/extensions/ble_state.dart';
import 'package:sgy_flutter/extensions/device_model_firmware_check.dart';
import 'package:sgy_flutter/extensions/get.dart';
import 'package:sgy_flutter/model/axo_data_model.dart';
import 'package:sgy_flutter/model/cycling_power_measurement_resp.dart';
import 'package:sgy_flutter/model/device_model.dart';
import 'package:sgy_flutter/model/dls_upload_model.dart';
import 'package:sgy_flutter/model/dls_upload_model_old.dart';
import 'package:sgy_flutter/model/pair_state.dart';
import 'package:sgy_flutter/model/product_type.dart';
import 'package:sgy_flutter/widget/app_dialog.dart';
import 'package:rxdart/rxdart.dart' as rx;
import 'package:synchronized/synchronized.dart';

class DetailLogic extends GetxController with BleState {
  // var ready = false.obs;

  StreamSubscription? _cyclingPowerServiceSubscription;
  StreamSubscription? _cyclingPowerService16Subscription;
  Rxn<DeviceModel> deviceModel = Rxn();

  // Rx<BluetoothConnectionState> connectionState =
  //     Rx(BluetoothConnectionState.disconnected);

  Rxn<AxoDataModel> axoDataModel = Rxn();

  var hasEnterPage = false;

  final enterPageLock = Lock();

  @override
  void onInit() {
    deviceModel(Get.arguments);
    printError(info: Get.arguments.toString());
    super.onInit();
  }

  @override
  void onReady() async{
    _cyclingPowerServiceSubscription = bleManager.cyclingPowerService.resp
        .listen(_onCyclingPowerMeasurementResp);
    _cyclingPowerService16Subscription = bleManager.cyclingPowerService16.resp
        .listen(_onCyclingPowerMeasurementResp);

    printInfo(info: "bleManager.cyclingPowerService16.isSupportNotify:${bleManager.cyclingPowerService16.isSupportNotify}");
    printInfo(info: "bleManager.cyclingPowerService.isSupportNotify:${bleManager.cyclingPowerService.isSupportNotify}");

    if (isDoubleSlide.value){
      if (bleManager.deviceModel?.productType == ProductType.dls){
        if (!HardwareVersion.isOldDevice(bleManager.deviceModel)){
          final pairState = await bleManager.getPairState();
          printInfo(info: "pairState:${pairState}");
          if (pairState != PairState.paired){
            loaderOverlay?.show(progress: "正在配对中".tr);
            try {
              await bleManager.startPair();
            } catch(e){
              printError(info: "$e");
            }finally{
              loaderOverlay?.hide();
            }
          }

        }
      }
    }
    WidgetsBinding.instance.addPostFrameCallback((_){
      if (!hasEnterPage){
        onLeftDeviceReady();
        onRightDeviceReady();
      }
    });




    super.onReady();
  }


  /**
   * 老的DLS设备数据接收
   */
  Stream<Pair<DlsUploadModelOld, DlsUploadModelOld?>> get dlsUploadDataOld{
    if (isDoubleSlide.value){
      return rx.CombineLatestStream.combine2<DlsUploadModelOld,
          DlsUploadModelOld,
          Pair<DlsUploadModelOld, DlsUploadModelOld?>>(bleManager.dlsUploadDataOld, rightBleManager!.dlsUploadDataOld, (l, r) {
            return Pair(l, r);

      });
    }else{
      throw Error();
    }

  }


  void _onCyclingPowerMeasurementResp(AxoDataModel? resp) {
    // printInfo(info: "${resp.toString()}");
    axoDataModel(resp);
  }

  @override
  void onLeftDeviceReady() async {
    await enterPageLock.synchronized(()async{
      printInfo(info: "onLeftDeviceReady");
      hasEnterPage = true;
      await oldDeviceChargingCheck(bleManager);
      await bleManager.enterPage();
    });

  }

  @override
  void onLeftDeviceUnavailable() {
    super.onLeftDeviceUnavailable();
  }

  @override
  void onRightDeviceReady() async{
    await oldDeviceChargingCheck(rightBleManager);
    await rightBleManager?.enterPage();
    super.onRightDeviceReady();
  }

  Future oldDeviceChargingCheck(BleManager? manager)async{
    //老设备
    try {
      final name = await manager?.nameService.readName();
      printInfo(info: "${manager.runtimeType} readName:${name}");
      if (name == "AXO" || name == "DLS" || name == "DLS_L" || name == "DLS_R") {
        if (Get.currentRoute == "/DetailPage"){
          Get.dialog(AppDialog(
              title: "提示".tr,
              message: "如果您无需升级设备，请断开充电器".tr,
              submit: "好的,我知道了!".tr), barrierDismissible: false);
        }

      }

      printError(info: "nameService:$name");
    } catch (e) {
      printError(info: "$e");
    }
  }

  void connect() {
    if (deviceModel.value != null) {
      bleManager.connect(deviceModel.value!);
    }
  }

  bool _isUserDisconnect = false;

  void disconnect() {
    if (deviceModel.value != null) {
      _isUserDisconnect = true;
      bleManager.userDisconnect(deviceModel.value!);
    }
  }

  @override
  void onClose() {
    _cyclingPowerServiceSubscription?.cancel();
    _cyclingPowerService16Subscription?.cancel();
    super.onClose();
  }
}
